<script setup>
import { ref, reactive, shallowRef } from "vue"; // 移除未使用的onMounted
import { getProductImageList } from "@/api/productImage";
import { getProductDetail } from "@/api/product";
import { addOrder } from "@/api/order";
import { pay } from "@/api/pay";
import { Picture as IconPicture, Plus } from "@element-plus/icons-vue";
import { useUserStore } from "@/stores";
import { formatTime } from "@/utils/format";

import { getProductTypeList } from "@/api/productType";
import { addProductImage } from "@/api/productImage";
import { addProduct } from "@/api/product";
import { upload, deleteFile } from "@/api/file";

import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css";

const emit = defineEmits(["success"]);

const userStore = useUserStore();
// 抽屉开关
const visibleDrawer = ref(false);
// 对话框开关（未使用，保留原逻辑）
const dialogFormVisible = ref(false);

// 获取商品类型列表
const productTypeList = ref([]);
// 存储商品数据
const productData = ref({});
// 存储商品图片
const productImages = ref([]);

// 表单引用（未使用，保留原逻辑）
const form = ref(null);

// 当前轮播图索引
const currentSlide = ref(0);
// 轮播图组件引用
const carousel = ref(null);
// 标记
const Tag = ref(null);

const product = {
  productTypeId: null,
  productName: "",
  description: "",
  price: null,
  stock: null,
  origin: "",
};

// 绑定表单对象
const formRef = ref(null);
// 表单验证规则
const formRules = reactive({
  productTypeId: {
    required: true,
    message: "请选择农产品类型",
    trigger: "change",
  },
  productName: { required: true, message: "请输入农产品名称", trigger: "blur" },
  price: { required: true, message: "请输入价格", trigger: "blur" },
  stock: { required: true, message: "请输入库存", trigger: "blur" },
  origin: { required: true, message: "请输入产地", trigger: "blur" },
});

const handleOpen = async (data, tag) => {
  visibleDrawer.value = true;
  Tag.value = tag;
  if (tag === "detail") {
    const product = await getProductDetail(data.productId);
    productData.value = product.data.data;
    const res = await getProductImageList(data.productId);
    productImages.value = res.data.data || [];
  } else {
    getProductType();
    productData.value = { ...product };
  }

  // 重置轮播图索引
  currentSlide.value = 0;
};

// 处理轮播图切换事件
const handleCarouselChange = (index) => {
  currentSlide.value = index;
};

const fileList = ref([]); // 上传文件列表

// 文件状态改变时调用
const onUploadFile = (file) => {
  console.log("上传文件选择后的回调", file);
  // 创建一个URL对象，将选择的文件转换为URL
  const url = URL.createObjectURL(file.raw);
  productImages.value.push({ imageUrl: url });
};

// 点击文件预览时调用
const onPreview = async (file) => {
  console.log("预览文件：", file);
  // 查找当前文件在 fileList 中的索引
  const currentIndex = fileList.value.findIndex(
    (item) => item.uid === file.uid
  );
  carousel.value.setActiveItem(currentIndex);
};

// 文件从文件列表移除时使用
const onRemove = (file) => {
  const currentIndex = fileList.value.findIndex(
    (item) => item.uid === file.uid
  );
  // 删除productImages中的对应数据
  productImages.value.splice(currentIndex, 1);
};

// 获取产品类型
const getProductType = async () => {
  const res = await getProductTypeList({
    current: 1,
    size: 999999,
  });
  productTypeList.value = res.data.data.data;
};

// 编辑器内容（双向绑定）
const html = ref("");

// 编辑器实例（必须用 shallowRef）
const editor = shallowRef(null);
// 标记编辑器是否已初始化
const isEditorInitialized = ref(false);
// 模式（default 或 simple）
const editorMode = ref("default");

// 工具栏配置
const toolbarConfig = ref({
  exclude: [],
});

// 编辑器配置
const editorConfig = ref({
  placeholder: "请输入内容...",
  // 上传图片配置
  MENU_CONF: {
    uploadImage: {
      async customUpload(file, insertFn) {
        const formData = new FormData();
        formData.append("file", file);
        const response = await upload(formData);
        insertFn(response.data.data, file.name, file.size);
      },
    },
  },
});

// 编辑器创建完成回调
const handleCreated = (editorInstance) => {
  editor.value = editorInstance;
  isEditorInitialized.value = true;
};

// 编辑器销毁回调
const handleDestroyed = () => {
  editor.value = null;
  isEditorInitialized.value = false;
};

// 确定
const handleSubmit = async () => {
  await formRef.value.validate();
  if (fileList.value.length == 0) {
    ElMessage.error("请上传图片");
    return;
  }
  const res = await addProduct(productData.value);
  const id = res.data.data;
  // 获取图片url,上传到数据库
  fileList.value.forEach(async (file, index) => {
    const formData = new FormData();
    formData.append("file", file.raw, file.name);
    const res = await upload(formData);
    const url = res.data.data;
    const res2 = await addProductImage({
      productId: id,
      imageUrl: url,
      sortOrder: index + 1,
    });
    if (res2.data.code != 200) {
      await deleteFile(url);
    }
  });
  emit("success");
  ElMessage.success("上传成功");
  handleCancel();
};

// 关闭抽屉
const handleCancel = () => {
  visibleDrawer.value = false;
  // 清空数据
  productData.value = {};
  productImages.value = [];
  fileList.value = [];
  // 重置轮播图索引
  currentSlide.value = 0;
};

// 向外暴露的方法
defineExpose({
  handleOpen,
});
</script>
<template>
  <div class="product-detail-container">
    <el-drawer
      title="农产品详情"
      v-model="visibleDrawer"
      direction="btt"
      size="100%"
      @close="handleCancel"
    >
      <div class="main-content">
        <el-row :gutter="30">
          <!-- 商品图片轮播区 -->
          <el-col :span="15">
            <div class="carousel-container">
              <el-carousel
                ref="carousel"
                height="350px"
                motion-blur
                :interval="7000"
                indicator-position="none"
                @change="handleCarouselChange"
              >
                <el-carousel-item
                  v-for="(item, index) in productImages"
                  :key="item.imageId || index"
                >
                  <el-image
                    style="width: 100%; height: 100%"
                    :src="item.imageUrl"
                    fit="contain"
                    preview-teleported
                    :preview-src-list="productImages.map((img) => img.imageUrl)"
                  >
                    <template #error>
                      <div class="image-placeholder">
                        <el-icon><icon-picture /></el-icon>
                        <span class="placeholder-text">暂无图片</span>
                      </div>
                    </template>
                  </el-image>
                </el-carousel-item>
              </el-carousel>

              <!-- 缩略图指示器 -->
              <div class="thumbnail-indicators" v-if="Tag == 'detail'">
                <div
                  v-for="(item, index) in productImages"
                  :key="item.imageId || index"
                  class="thumbnail-item"
                  :class="{ active: currentSlide === index }"
                  @click="carousel.setActiveItem(index)"
                >
                  <el-image
                    :src="item.imageUrl"
                    fit="contain"
                    style="width: 100%; height: 100%"
                  />
                </div>
              </div>
              <div class="thumbnail-indicators" v-if="Tag == 'add'">
                <el-upload
                  multiple
                  list-type="picture-card"
                  v-model:file-list="fileList"
                  :auto-upload="false"
                  :on-change="onUploadFile"
                  :on-preview="onPreview"
                  :on-remove="onRemove"
                  accept=".jpg,.jpeg,.png"
                  :limit="8"
                >
                  <el-icon class="thumbnail-item"><Plus /></el-icon>
                </el-upload>
              </div>
            </div>
          </el-col>

          <!-- 商品信息区 -->
          <el-col :span="9">
            <div class="product-info" v-if="Tag == 'detail'">
              <p class="title">农产品信息</p>
              <div class="product-name">
                <el-tooltip
                  placement="top"
                  :content="productData.productName"
                  effect="light"
                >
                  <span>
                    {{ productData.productName || "商品名称" }}
                  </span>
                </el-tooltip>
              </div>
              <el-form v-model="productData" label-width="90px">
                <el-form-item class="product-price" label="单价:">
                  <span class="price-value"
                    >¥{{ productData.price?.toFixed(2) || "0.00" }}</span
                  >
                </el-form-item>

                <el-form-item label="库存:">
                  <span class="stock-value">{{ productData.stock }} 件</span>
                </el-form-item>

                <el-form-item label="状态:">
                  <el-tag v-if="productData.status === 0" type="primary"
                    >待审核</el-tag
                  >
                  <el-tag v-else-if="productData.status === 1" type="warning"
                    >不通过</el-tag
                  >
                  <el-tag v-else-if="productData.status === 2" type="success"
                    >上架</el-tag
                  >
                  <el-tag v-else-if="productData.status === 3" type="danger"
                    >上架</el-tag
                  >
                </el-form-item>

                <el-form-item label="销量:">
                  <span class="stock-value"
                    >{{ productData.salesVolume }} 件</span
                  >
                </el-form-item>
                <el-form-item label="类型:">
                  <span class="stock-value"
                    >{{ productData.productTypeName }}
                  </span>
                </el-form-item>
                <el-form-item label="产地:">
                  <span class="stock-value">{{ productData.origin }} </span>
                </el-form-item>
                <el-form-item label="创建时间:">
                  <span class="stock-value">
                    {{ formatTime(productData.createTime) }}
                  </span>
                </el-form-item>
              </el-form>
            </div>

            <!-- 上传农产品时要输入的参数 -->
            <div class="product-info2" v-if="Tag == 'add'">
              <p class="title">农产品信息</p>
              <el-form
                :model="productData"
                label-width="80px"
                ref="formRef"
                :rules="formRules"
              >
                <el-form-item label="名称" prop="productName">
                  <el-input
                    v-model="productData.productName"
                    placeholder="请输入"
                    :autosize="{ minRows: 2, maxRows: 6 }"
                    type="textarea"
                  ></el-input>
                </el-form-item>
                <el-form-item label="单价" prop="price">
                  <el-input
                    placeholder="请输入"
                    v-model="productData.price"
                  ></el-input>
                </el-form-item>
                <el-form-item label="库存" prop="stock">
                  <el-input
                    placeholder="请输入"
                    v-model="productData.stock"
                  ></el-input>
                </el-form-item>
                <el-form-item label="类型" prop="productTypeId">
                  <el-select
                    v-model="productData.productTypeId"
                    style="width: 60%"
                  >
                    <el-option
                      v-for="item in productTypeList"
                      :key="item.typeId"
                      :label="item.typeName"
                      :value="item.typeId"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="产地" prop="origin">
                  <el-input
                    placeholder="请输入"
                    v-model="productData.origin"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleSubmit">
                    确定
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-col>
        </el-row>

        <!-- 商品描述区域 -->
        <div class="product-description" v-if="Tag == 'detail'">
          <h3 class="description-title">农产品介绍</h3>
          <div
            class="description-content"
            v-html="productData.description"
          ></div>
        </div>

        <!-- 添加商品时用到 -->
        <div class="product-description" v-if="Tag == 'add'">
          <h3 class="description-title">农产品介绍</h3>
          <div class="description-content">
            <!-- 工具栏：仅在编辑器实例存在时渲染 -->
            <Toolbar
              v-if="editor"
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="editorMode"
            />

            <!-- 编辑器内容区域 -->
            <Editor
              v-model="productData.description"
              :editor="editor"
              :defaultConfig="editorConfig"
              :mode="editorMode"
              @onCreated="handleCreated"
              @onDestroyed="handleDestroyed"
              class="editor-content"
            />
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<style scoped>
/* 抽屉基础样式（生效） */
:deep(.el-drawer__header) {
  margin-bottom: 0;
}
:deep(.el-upload-list__item) {
  width: 80px;
  height: 80px;
}
:deep(.el-upload--picture-card) {
  order: -1;
  width: 80px;
  height: 80px;
  margin-right: 8px;
}
:deep(.el-upload-list--picture-card) {
  flex-wrap: nowrap;
}
.product-info .el-form-item {
  margin-bottom: 10px;
}

/* 主内容容器样式（生效） */
.main-content {
  padding: 0 20px;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

/* 轮播图容器样式（生效） */
.carousel-container {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  background-color: #f2f6fc;
  padding: 20px;
}

/* 图片加载失败占位样式（生效） */
.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  color: #999;
}
.placeholder-text {
  margin-top: 15px;
  font-size: 14px;
}

/* 缩略图指示器样式（生效） */
.thumbnail-indicators {
  display: flex;
  gap: 10px;
  padding: 15px 0 5px;
  overflow-x: auto;
  scrollbar-width: thin;
}
.thumbnail-item {
  border: 1px solid #ded6d6;
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  opacity: 0.7;
  transition: all 0.2s;
  flex-shrink: 0;
}
.thumbnail-item.active {
  opacity: 1;
  border: 2px solid #409eff;
}
:deep(.thumbnail-item el-image) {
  /* 修复图片样式穿透，确保生效 */
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 商品信息容器样式（生效） */
.product-info {
  box-sizing: border-box;
  background: rgb(236, 245, 255);
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.product-info .title {
  margin: 0 0 15px;
  line-height: 1;
}

.product-info2 {
  box-sizing: border-box;
  background: rgb(236, 245, 255);
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  height: 100%;
}

/* 商品名称样式（生效） */
.product-name {
  border-radius: 4px;
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
  padding: 5px 30px;
  height: 70px;
}
.product-name span {
  color: rgb(121, 187, 255);
  font-size: 16px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 限制显示的行数为3行 */
  -webkit-box-orient: vertical; /* 设置盒子内的内容垂直排列 */
  overflow: hidden; /* 隐藏超出的内容 */
}

/* 商品单价样式（生效） */
.price-value {
  color: #f56c6c;
  font-weight: 700;
}

.stock-value {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
  color: rgb(121, 187, 255);
}

/* 商品描述区域样式（生效） */
.product-description {
  margin-top: 20px;
  background-color: rgb(236, 245, 255);
  border-radius: 8px;
  padding: 1px 30px 30px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
}
.description-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}
.description-content {
  color: #666;
  line-height: 1.8;
  font-size: 14px;
}
.description-content img {
  max-width: 100%;
  height: auto;
  margin: 15px 0;
}

/* 富文本编辑器样式 */
.editor-content {
  width: 100%;
  min-height: 400px;
  box-sizing: border-box;
  background-color: #fff;
}

/* 响应式调整（生效） */
@media (max-width: 768px) {
  .main-content {
    padding: 10px;
  }
  .carousel-container {
    height: auto;
  }
  :deep(.el-carousel) {
    /* 修复轮播图高度穿透 */
    height: 300px !important;
  }
  .product-name {
    font-size: 18px;
  }
  .product-description {
    padding: 20px 15px;
  }
}
</style>
